#! /usr/bin/env python
# -*- coding:utf-8 -*-
# ====#====#====#====

# 导包
import os
import time
import smtplib
from common.log import logger
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart

# 定义一个邮件发送的类
class SendEmail(object):
    # 定义初始化函数，获取邮件发送的数据
    def __init__(self):
        # 定义发件人
        self.sender = '1033353613@qq.com'
        # 定义收件人
        self.receiver = '1033353613@qq.com'
        # 定义发件主题
        t = time.strftime('%Y_%m_%d_%H_%M_%S', time.localtime())
        self.title = '接口自动化测试报告' + t
        # 定义发件服务器
        self.server = 'smtp.qq.com'
        # 发件人用户名及密码
        self.username = '1033353613@qq.com'
        self.password = 'kptqxaqnhsmpbdjc'

    # 定义组装邮件函数
    def email_content(self, file):
        # 组装邮件内容和标题
        with open(file, 'rb') as f:
            mail_body = f.read()
            # 组装邮件内容和标题
            self.msg = MIMEMultipart()
            # 添加附件内容
            att = MIMEText(mail_body, 'plain', 'utf-8')
            att['Content-Type'] = 'application/octet-stream'
            att['Content-Disposition'] = 'attachment; filename=report.html'
            self.msg.attach(att)
        # 添加文件的文本内容
            conetent = '自动化测试报告详情，请查收'
            self.msg.attach(MIMEText(conetent, 'plain', 'UTF-8'))
            self.msg['Subject'] = Header(self.title, 'UTF-8')
            self.msg['Form'] = self.sender
            self.msg['To'] = '.'.join(self.receiver)

    # 定义发送邮件方法
    def send_email(self, file):
        self.email_content(file)
        try:
            # 实例化smtplib类
            smtp = smtplib.SMTP()
            # 链接smtp服务器
            smtp.connect(self.server)
            # 登录邮箱
            smtp.login(self.username, self.password)
            # 设置发件人、收件人和发件主题
            smtp.sendmail(self.sender, self.receiver, self.msg.as_string())
        except Exception as msg:
            logger.info('邮件发送失败！%s' % msg)
        else:
            logger.info('邮件发送成功')
        finally:
            smtp.quit()
